package com.colorfruit.framework.validate;

import com.alibaba.fastjson.JSONObject;
import com.colorfruit.framework.common.util.ValidationUtil;
import com.colorfruit.framework.model.sys.ValidateException;
import com.colorfruit.framework.model.sys.ValidationResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

import static com.colorfruit.framework.model.enums.ValidTypeEnum.THROW_EXCEPTION;


/**
 * 业务描述：参数校验
 *
 * @Auther: chenjiayuan
 * @Date: create in 2018/7/6 14
 * @Description:
 */
@Slf4j
public class RequestBodyValidResolver implements HandlerMethodArgumentResolver{
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestBodyWithValid.class);
    }

    @Nullable
    @Override
    public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
        log.info("===========开始对[{}接口]做参数校验=============",parameter.getMember().getName());
        RequestBodyWithValid paramValid = parameter.getParameterAnnotation(RequestBodyWithValid.class);
        Object entity = null;
        if (paramValid.decipher().equals(THROW_EXCEPTION)){
            //验证不通过则直接抛异常;
            String content = new String(IOUtils.toByteArray(webRequest.getNativeRequest(HttpServletRequest.class).getInputStream()), "UTF-8");
            entity = !StringUtils.isEmpty(content)?JSONObject.parseObject(content,parameter.getParameterType()):JSONObject.parseObject("{}",parameter.getParameterType());
            if (entity!=null){
                ValidationResult result = ValidationUtil.validateEntity(entity);
                if (result.getHasErrors()){
                    throw  new ValidateException(result.toMsgString());
                }
            }else if (paramValid.required()==true){
                throw new ValidateException("参数不能为空！");
            }
        }
        return entity;
    }
}
